import React from 'react';
import { Modal, Form, Input } from 'antd';

const FormItem = Form.Item;

class Password extends React.Component {
  constructor (props) {
    super(props);
    this.state = {};
    this.onOK = this.onOK.bind(this);
  }
  // 验证两次输入密码是否一致
  compareToFirstPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('newPassword')) {
      callback('两次输入密码不一致');
    } else {
      callback();
    }
  }

  onOK () {
    const { onOK, form, onCancel, record, getList } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        delete values.confirm;
        onOK({ ...values, name: record.name }).then(() => {
          onCancel();
          getList();
        });
      }
    });
  }

  render () {
    const { onCancel, form, loading } = this.props;
    const { getFieldDecorator } = form;
    const modalOpts = {
      confirmLoading: loading,
      title: '修改密码',
      width: 500,
      visible: true,
      maskClosable: false,
      okText: '确定',
      cancelText: '取消',
      onOk: this.onOK,
      onCancel
    };
    const formItemLayout = {
      labelCol: {
        span: 6
      },
      wrapperCol: {
        span: 18
      }
    };
    return (
      <Modal {...modalOpts}>
        <Form>
          <FormItem
            label='旧密码'
            {...formItemLayout}
          >
            {
              getFieldDecorator('oldPassword', {
                initialValue: '',
                rules: [{ required: true, message: '请填写旧密码' }]
              })(
                <Input
                  type='password'
                  maxLength={30}
                  placeholder='旧密码'
                />
              )
            }
          </FormItem>
          <FormItem
            label='新密码'
            {...formItemLayout}
          >
            {
              getFieldDecorator('newPassword', {
                initialValue: '',
                rules: [{ required: true, message: '请填写新密码' }]
              })(
                <Input
                  type='password'
                  maxLength={30}
                  placeholder='新密码'
                />
              )
            }
          </FormItem>
          <FormItem
            label='重复新密码'
            {...formItemLayout}
          >
            {
              getFieldDecorator('confirm', {
                initialValue: '',
                rules: [
                  { required: true, message: '请重复新密码' },
                  {
                    validator: this.compareToFirstPassword
                  }
                ]
              })(
                <Input
                  type='password'
                  maxLength={30}
                  placeholder='重复新密码'
                />
              )
            }
          </FormItem>
        </Form>
      </Modal>
    );
  }
}

export default Form.create()(Password);
